<template>
	<div class="search-container">
		<div class="search-area">
			<el-input clearable autofocus ref="searchInput" class="search-input" v-model="searchQuery"
				placeholder="搜索商品" @keyup.enter="searchProducts" />
			<el-button @click="searchProducts" class="search-button" :loading="loading">搜索商品</el-button>
		</div>

		<div class="product-list" v-if="prodList.length">
			<el-table :data="prodList" style="width: 100%" :height="computedTableHeight()">
				<el-table-column prop="name" label="商品名称" />
				<el-table-column prop="quantity" label="商品数量" />
				<!-- <el-table-column prop="image" label="商品图片" /> -->
				<!-- <el-table-column prop="remark" label="商品备注" /> -->
				<el-table-column prop="price" label="商品价格">
					<template #default="scope">
						<div class="price-box">
							￥{{ scope.row.price }}
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="action" label="操作" align="right">
					<template #default="scope">
						<el-button type="primary" @click="handleProduct(scope.row)">详情</el-button>
						<el-button type="danger" @click="handleDelete(scope.$index)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-card class="product-card" shadow="hover" v-if="!prodList.length">
			<el-empty description="请搜索商品" />
		</el-card>

		<div class="total-box" v-if="prodList.length">
			<div class="total-title">合计：{{ totalPrice }}元</div>
			<div class="right">
				<el-button type="danger" @click="handleClear">清空</el-button>
				<el-button type="primary" @click="handleSubQuantity">出库</el-button>
			</div>
		</div>

		<el-dialog v-model="productDialog" title="商品详情" width="50%">
			<el-card class="product-card" shadow="hover">
				<div class="product-image-container">
					<el-image v-for="(image, index) in product.image" :src="image" class="product-image" :key="index" />
				</div>

				<div class="row">
					<div class="col">
						<div class="label">商品名称</div>
						<div class="value">{{ product.name }}</div>
					</div>
					<div class="col">
						<div class="label">商品编码</div>
						<div class="value">{{ product.itemCode }}</div>
					</div>
				</div>
				<div class="row">
					<div class="col">
						<div class="label">商品类别</div>
						<div class="value">{{ product.category }}</div>
					</div>
					<div class="col">
						<div class="label">商品单位</div>
						<div class="value">{{ product.unit }}</div>
					</div>
				</div>
				<div class="row">
					<div class="col">
						<div class="label">商品价格</div>
						<div class="value price">￥{{ product.price }}</div>
					</div>
				</div>
				<div class="row">
					<div class="col">
						<div class="label">商品数量</div>
						<div class="value quantity">
							<div class="quantity-input">
								<div class="quantity-input-value">{{ product.quantity }}</div>
								<div class="quantity-input-button">
									<el-button type="primary" size="large" @click="addQuantity"
										:loading="addLoading">增加</el-button>
									<el-button type="warning" size="large" @click="subQuantity"
										:loading="subLoading">减少</el-button>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col">
						<div class="label">商品备注</div>
						<div class="value">{{ product.remark }}</div>
					</div>
				</div>
			</el-card>
		</el-dialog>
	</div>
</template>

<script setup>
import api from '@/request/index'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'

const router = useRouter()

let loading = ref(false)
let searchInput = ref(null)
let productDialog = ref(false)

const product = ref({
	image: '',
	itemCode: '',
	name: '',
	category: '',
	unit: '',
	quantity: 0,
	minQuantity: 0,
	maxQuantity: 0,
	price: 0,
	status: true,
	remark: ''
})
const oldQuery = ref('')
const searchQuery = ref('')
const prodList = ref([])

const totalPrice = computed(() => {
	return prodList.value.reduce((acc, item) => acc + Number(item.price), 0)
})

onMounted(() => {
	searchInput.value.focus()
	console.log(computedTableHeight())
})

watch(
	() => searchQuery.value,
	val => {
		if (val === '') {
			oldQuery.value = ''
		}
	}
)

const computedTableHeight = () => {
	const totalHeight = document.documentElement.clientHeight - 296
	return totalHeight + 'px'
}

const searchProducts = async () => {
	console.log('搜索商品:', searchQuery.value, oldQuery.value)
	if (searchQuery.value === '') {
		ElMessage.error('请输入商品编码')
		return
	}
	if (product.value.itemCode) resetProduct()
	if (oldQuery.value && oldQuery.value !== searchQuery.value) {
		searchQuery.value = searchQuery.value.replace(oldQuery.value, '')
	}
	oldQuery.value = searchQuery.value
	try {
		loading.value = true
		const { data } = await api.searchProduct({
			itemCode: searchQuery.value
		})
		if (data) {
			data.image = data.image.split(';')
			product.value = data
			prodList.value.unshift({ ...data, num: 1 })
		} else {
			ElMessage.error('未找到商品')
		}
	} catch (error) {
		console.log(error, error.message)
		if (error.message === "商品不存在") {

			ElMessageBox.confirm('商品不存在，是否添加商品？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				router.push({
					path: '/store/product/add',
					query: {
						itemCode: searchQuery.value
					}
				})
			})

		}
	} finally {
		loading.value = false
	}
}

const resetProduct = () => {
	product.value = {
		image: '',
		itemCode: '',
		name: '',
		category: '',
		unit: '',
		quantity: 0,
		minQuantity: 0,
		maxQuantity: 0,
		price: 0,
		status: true,
		remark: ''
	}
}

let addLoading = ref(false)
const addQuantity = async () => {
	let num = product.value.quantity + 1
	try {
		addLoading.value = true
		await api.productEdit(product.value.id, {
			quantity: num,
			type: 'quantity',
			typeValue: 'add'
		})
		product.value.quantity = num
		ElMessage.success('操作成功')
	} catch (error) {
		console.log(error)
	} finally {
		addLoading.value = false
	}
}

let subLoading = ref(false)
const subQuantity = async () => {
	let num = product.value.quantity - 1
	try {
		subLoading.value = true
		await api.productEdit(product.value.id, {
			quantity: num,
			type: 'quantity',
			typeValue: 'sub'
		})
		product.value.quantity = num
		ElMessage.success('操作成功')
	} catch (error) {
		console.log(error)
	} finally {
		subLoading.value = false
	}
}

const handleProduct = (row) => {
	product.value = row
	productDialog.value = true
}

const handleClear = () => {
	prodList.value = []
}

const handleDelete = cindex => {
	prodList.value = prodList.value.filter((item, index) => index !== cindex)
	ElMessage.success('清楚商品成功')
}

const handleSubQuantity = async () => {
	// 合并相同itemCode的商品，数量相加
	const mergedList = []
	const map = new Map()
	prodList.value.forEach(item => {
		if (map.has(item.itemCode)) {
			map.get(item.itemCode).num += 1
		} else {
			// 这里要深拷贝，避免影响原数组
			map.set(item.itemCode, { ...item })
		}
	})
	map.forEach(val => mergedList.push(val))

	await Promise.all(mergedList.map(item => {
		return api.productEdit(item.id, {
			quantity: item.quantity - item.num,
			type: 'quantity',
			typeValue: 'sub'
		})
	})).then(() => {
		prodList.value = []
		ElMessage.success('出库成功')
	}).catch(() => {
		ElMessage.error('出库失败')
	})
}
</script>

<style scoped lang="less">
.search-container {
	max-width: 100%;
	margin: 0 auto;
	position: relative;
}

.search-area {
	margin: 0 0 30px 0;
	max-width: 100%;
	display: flex;
	background-color: #f0f4ff;
	padding: 15px;
	border-radius: 8px;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.search-input {
	flex: 1;
	margin-right: 10px;
	border: 1px solid #409eff;
	border-radius: 4px;

	&:focus {
		border-color: #66b1ff;
		box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
	}
}

.search-button {
	background-color: #409eff;
	color: white;
	border-radius: 4px;

	&:hover {
		background-color: #66b1ff;
	}
}

.product-list {
	.price-box {
		color: red;
		font-size: 16px;
		font-weight: bold;
	}
}


.product-card {
	width: 100%;
	border-radius: 12px;
	box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
	transition: transform 0.2s, box-shadow 0.2s;
	background-color: #ffffff;
	margin-bottom: 10px;

	.info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 20px;

		.name {
			font-size: 20px;
			font-weight: bold;
		}

		.price {
			flex: 1;
			font-size: 20px;
			font-weight: bold;
			color: red;
			text-align: right;
		}
	}

	.product-image-container {
		width: 100%;
		display: flex;
		gap: 10px;
		flex-wrap: wrap;
		margin-bottom: 15px;

		.el-image {
			width: 100px;
			height: 100px;
			border-radius: 8px;
		}
	}

	.row {
		gap: 10px;
		display: flex;
		flex-direction: row;
		margin-bottom: 15px;
	}

	.col {
		flex-shrink: 0;
		min-height: 40px;
		flex: 1;
		gap: 10px;
		display: flex;
		align-items: center;
		border-radius: 4px;
		border: 2px solid #e4e4e4;

		.label {
			width: 120px;
			height: 100%;
			flex-shrink: 0;
			padding: 0 10px;
			background-color: #f0f4ff;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #202427;
			font-size: 16px;
		}

		.price {
			color: red;
			font-size: 20px;
			font-weight: bold;
		}

		.quantity {
			color: green;
			font-size: 20px;
			font-weight: bold;
		}

		.value {
			flex: 1;
			padding: 10px;
			word-wrap: break-word;
			/* 允许长单词换行 */
			overflow-wrap: break-word;
			/* 兼容性处理 */

			.quantity-input {
				display: flex;
				align-items: center;
				justify-content: center;

				.quantity-input-value {
					flex: 1;
				}

				// .quantity-input-button {}
			}
		}
	}
}

.total-box {
	box-sizing: border-box;
	width: 100%;
	height: 72px;
	padding: 20px;
	border-radius: 10px;
	background-color: #fff;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 30px;
	position: sticky;
	bottom: -18px;
	left: 0;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);

	.total-title {
		color: red;
		font-size: 24px;
		font-weight: bold;
	}

	.right {
		display: flex;
	}
}
</style>
